﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using System.Collections.Generic;
using Yqd.Enm;
using Newtonsoft.Json.Linq;
using Yqd.Dto;
using Yqd.Core;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxMySuperviseController : Controller
    {
        YqdContext ctx;

        public WxMySuperviseController(YqdContext ctx)
        {
            this.ctx = ctx;
        }

        [User]
        public ActionResult GetHSearch()
        {
            var items = new List<object>();
            items.AddRange(Enum.GetNames(typeof(事项类型)).Select(q => new
            {
                name = q,
                value = Enum.Parse(typeof(事项类型), q)
            }));
            var zx = Form.GetInt("zx", 0);
            var years = new List<object>();
            years.Add(new { name = "全部", value = 0 });
            for (var i = DateTime.Now.Year; i >= 2021; i--)
            {
                years.Add(new { name = i + "年", value = i });
            }
            //if (zx != 1)
            //{
            //    years.Remove(new { name = DateTime.Now.Year + "年", value = DateTime.Now.Year });
            //}
            var TaskType = new List<object>();
            TaskType.Add(new { name = "全部", value = "" });
            TaskType.AddRange(Enum.GetNames(typeof(任务类型)).Select(q => new
            {
                name = q,
                value = Enum.Parse(typeof(任务类型), q)
            }));
            return this.ToJson(new
            {
                success = true,
                items,
                TaskType,
                years
            });
        }

        [User]
        public ActionResult GetSearch()
        {
            var ItemType = Form.GetInt("ItemType", (int)事项类型.钉办督导);
            var states = new List<object>();
            states.Add(new { name = "全部", value = "0" });
            foreach (int item in Enum.GetValues(typeof(督导状态)))
            {
                if (ItemType > 10 && item == 50) continue;
                states.Add(new
                {
                    name = Enum.GetName(typeof(督导状态), item),
                    value = item
                });
            }
            var depts = new List<object>();
            depts.Add(new { name = "全部", value = "" });
            var data = new List<long>();
            var tasks = new List<object>();
            tasks.Add(new { name = "全部", value = "" });
            switch ((事项类型)ItemType)
            {
                case 事项类型.钉办督导:
                    data.AddRange(ctx.Yqd_Supervise.Where(it=>it.IsDel == 0).Select(it => it.TaskID));
                    depts.AddRange(ctx.Yqd_Task.Where(it => data.Contains(it.TaskID)).Select(it => new
                    {
                        value = it.LeaderUnitCode,
                        name = it.LeaderUnitName
                    }).Distinct());
                    break;
                case 事项类型.协同管理:
                    data.AddRange(ctx.Yqd_Coordinate.Where(it=>it.IsDel == 0).Select(it => it.TaskID));
                    depts.AddRange(ctx.Yqd_Task.Where(it => data.Contains(it.TaskID)).Select(it => new
                    {
                        value = it.LeaderUnitCode,
                        name = it.LeaderUnitName
                    }).Distinct());
                    break;
                case 事项类型.精准督查:
                    data.AddRange(ctx.Yqd_ExactSupervise.Select(it => it.TaskID));
                    depts.AddRange(ctx.Yqd_Task.Where(it => data.Contains(it.TaskID)).Select(it => new
                    {
                        value = it.LeaderUnitCode,
                        name = it.LeaderUnitName
                    }).Distinct());
                    break;
                case 事项类型.专项交办:
                    var codes = ctx.Yqd_Assign.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.LeadUnit).ToArray();
                    depts.AddRange(ctx.Yqd_Unit.Where(it => codes.Contains(it.UnitCode)).Select(it => new { value = it.UnitCode, name = it.Name }).Distinct());
                    var tks = ctx.Yqd_SpecialTask.Where(it => it.IsDel == 0 && it.TaskType == 专项类型.专项交办 && it.Status == 栏目状态.正常).OrderByDescending(it => it.Instime);
                    var tps = ctx.Database.SqlQuery<Adp.Models.Tcm_Config>("select * from Tcm_Config where PlusID='Yqd' and Groupname='督查端' and ConfigTypeName='督查类型'");
                    var cIDs = new List<long>();
                    foreach (var t in tks)
                    {
                        //if (t.ConfigID > 0)
                        //{
                        //    if (cIDs.Contains(t.ConfigID)) continue;
                        //    var tpsModel = tps.FirstOrDefault(m => m.ConfigID == t.ConfigID);
                        //    if(tpsModel != null)
                        //    {
                        //        tasks.Add(new
                        //        {
                        //            name = tpsModel.Name,
                        //            value =t.TaskID
                        //        });
                        //    }
                        //    //tasks.Add(new
                        //    //{
                        //    //    name = tps.FirstOrDefault(m => m.ConfigID == t.ConfigID)?.Name,
                        //    //    value = 0,
                        //    //    children = tks.Where(it => it.ConfigID == t.ConfigID).Select(it => new
                        //    //    {
                        //    //        name = it.Name,
                        //    //        value = it.TaskID
                        //    //    })
                        //    //});
                        //    cIDs.Add(t.ConfigID);
                        //}
                        //else
                        //{
                        //    tasks.Add(new
                        //    {
                        //        name = t.Name,
                        //        value = t.TaskID
                        //    });
                        //}
                        tasks.Add(new
                        {
                            name = t.Name,
                            value = t.TaskID
                        });
                    }
                    break;
                case 事项类型.专项督查:
                    var codes1 = ctx.Yqd_Assign.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.LeadUnit).ToArray();
                    depts.AddRange(ctx.Yqd_Unit.Where(it => codes1.Contains(it.UnitCode)).Select(it => new { value = it.UnitCode, name = it.Name }).Distinct());
                    var tks1 = ctx.Yqd_SpecialTask.Where(it => it.IsDel == 0 && it.TaskType == 专项类型.专项督查 && it.Status == 栏目状态.正常).OrderByDescending(it => it.Instime);
                    //var tps1 = ctx.Database.SqlQuery<Adp.Models.Tcm_Config>("select * from Tcm_Config where PlusID='Yqd' and Groupname='督查端' and ConfigTypeName='督查类型'");
                    var cIDs1 = new List<long>();
                    foreach (var t in tks1)
                    {
                        //if (t.ConfigID > 0)
                        //{
                        //    if (cIDs.Contains(t.ConfigID)) continue;
                        //    var tpsModel = tps.FirstOrDefault(m => m.ConfigID == t.ConfigID);
                        //    if(tpsModel != null)
                        //    {
                        //        tasks.Add(new
                        //        {
                        //            name = tpsModel.Name,
                        //            value =t.TaskID
                        //        });
                        //    }
                        //    //tasks.Add(new
                        //    //{
                        //    //    name = tps.FirstOrDefault(m => m.ConfigID == t.ConfigID)?.Name,
                        //    //    value = 0,
                        //    //    children = tks.Where(it => it.ConfigID == t.ConfigID).Select(it => new
                        //    //    {
                        //    //        name = it.Name,
                        //    //        value = it.TaskID
                        //    //    })
                        //    //});
                        //    cIDs.Add(t.ConfigID);
                        //}
                        //else
                        //{
                        //    tasks.Add(new
                        //    {
                        //        name = t.Name,
                        //        value = t.TaskID
                        //    });
                        //}
                        tasks.Add(new
                        {
                            name = t.Name,
                            value = t.TaskID
                        });
                    }
                    break;
            }
            return this.ToJson(new
            {
                success = true,
                states,
                depts,
                tasks
            });
        }

        [User]
        public ActionResult GetList()
        {
            var ItemType = Form.GetInt("ItemType", (int)事项类型.钉办督导);
            var status = Form.GetInt("status");
            var code = Form.GetString("code");
            var year = Form.GetInt("Year");
            var taskID = Form.GetLong("TaskID");
            var key = Form.GetString("key");
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 5);
            var sql = "1=1";
            var zx = (事项类型)ItemType == 事项类型.专项交办 || (事项类型)ItemType == 事项类型.专项督查;
            if (status > 0)
            {
                switch ((督导状态)status)
                {
                    case 督导状态.当前待办:
                        sql += " and [SuperviseID] not in(select [ItemID] from Yqd_Assign where ItemType=" + (int)事项类型.钉办督导+")";
                        break;
                    case 督导状态.正常推进:
                        sql += " and [SuperviseID] in(select [ItemID] from Yqd_Assign where ItemType=" + (int)事项类型.钉办督导 + ") and [Status] in(" + (int)任务状态.预警 + "," + (int)任务状态.正常推进 + "," + (int)任务状态.滞后 + ")";
                        break;
                    case 督导状态.滞后:
                        sql += " and [Status]=" + (int)任务状态.滞后;
                        break;
                    case 督导状态.已完成:
                        sql += " and [Status]=" + (int)任务状态.已完成;
                        break;
                    case 督导状态.钉办事项:
                        if (ItemType == (int)事项类型.钉办督导)
                            sql += " and [SuperviseType]=" + (int)督导类型.钉办;
                        break;
                }
            }
            if (code.Trim() != "")
            {
                sql += zx ? " and SuperviseID in(select ItemID from Yqd_Assign where ItemType =" + (int)事项类型.专项交办 + " and LeadUnit='" + code + "')" : " and TaskID in(select TaskID from Yqd_Task where LeaderUnitCode='"+ code + "')";
            }
            if (key.Trim() != "")
            {
                sql += " and TaskID in(select TaskID from Yqd_SpecialTask where IsDel=0 and lower(ltrim(rtrim([Name]))) like  '%" + key.ToLower().Trim() + "%' )";
            }
            if (year > 0)
            {
                sql += " and year(Instime)=" + year;
            }
            switch ((事项类型)ItemType)
            {
                case 事项类型.钉办督导:
                    if ((督导状态)status != 督导状态.钉办事项)
                    {
                        sql += " and [SuperviseType]!=" + (int)督导类型.钉办;
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID, (case when SuperviseType= 10 then '钉办' else '督导' end) as Tag, Content, Status from Yqd_Supervise where " + sql + " and isdel=0 and [TaskID]>0 and EmployeeCode in (select EmployeeCode from Yqd_User where RealtionEmployeeCode like '%"+ WxUser.LogonInfo.EmployeeCode + "%' or employeeCode='"+ WxUser.LogonInfo.EmployeeCode + "') order by Instime desc";
                    break;
                case 事项类型.协同管理:
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, CooperativeID, '协同' as Tag, Item as Content from Yqd_Cooperative where " + sql + " and isdel=0 order by Instime desc";
                    break;
                case 事项类型.精准督查:
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID, '精准督查' as Tag, Problem as Content, Status from Yqd_ExactSupervise where isDel=0 and " + sql + " order by Instime desc";
                    break;
                case 事项类型.专项交办:
                    if (taskID > 0) sql += " and [TaskID]=" + taskID;
                    zx = true;
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID,TemplateID,TemplateData, '专项交办' as Tag, Status from Yqd_SpecialSupervise where isDel=0 and " + sql + " and TaskType="+(int)专项类型 .专项交办+ " order by Instime desc";
                    break;
                case 事项类型.专项督查:
                    if (taskID > 0) sql += " and [TaskID]=" + taskID;
                    zx = true;
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID,TemplateID,TemplateData, '专项督查' as Tag, Status from Yqd_SpecialSupervise where isDel=0 and " + sql + " and TaskType=" + (int)专项类型.专项督查 + " order by Instime desc";
                    break;
            }
            var data = ctx.Database.SqlQuery<SuperData>(sql);
            var rs = new List<object>();
            if (zx)
            {
                var tasks = ctx.Yqd_SpecialTask.Where(it => it.IsDel == 0).Select(it => new { it.TaskID, it.Name }).ToList();
                var tps = ctx.Yqd_SpecialTemplate.Select(it => new { it.TemplateID, it.Fields }).ToList();
                var scheme = ctx.Yqd_Scheme.Where(it => it.ItemType == 事项类型.专项交办).Select(it => new { it.ItemID, it.JobTarget }).ToList();
                foreach (var d in data)
                {
                    string TaskName = "", Content = "";
                    JObject Targets = null;
                    var task = tasks.FirstOrDefault(it => it.TaskID == d.TaskID);
                    if (task != null) TaskName = task.Name;
                    Content = string.Join(" - ", scheme.Where(it => it.ItemID == d.SuperviseID).Select(it => it.JobTarget));
                    var f = tps.FirstOrDefault(it => it.TemplateID == d.TemplateID);
                    var fs = new JArray();
                    if (f != null && f.Fields.HasValue()) fs = JArray.Parse(f.Fields);
                    var TemplateData = d.TemplateData;
                    if (TemplateData.HasValue())
                    {
                        Targets = JObject.Parse(TemplateData);
                    }
                    var Fields = new List<object>();
                    if (Targets != null)
                    {
                        foreach (var o in fs)
                        {
                            var keys = o["FieldID"].ToString();
                            Fields.Add(new
                            {
                                text = o["Name"]?.ToString() ?? "",
                                value = Targets[keys]?.ToString() ?? ""
                            });
                        }
                    }
                    rs.Add(new
                    {
                        d.Num,
                        d.TaskID,
                        d.SuperviseID,
                        TaskName,
                        Fields,
                        d.Tag,
                        DealStatus = Enum.GetName(typeof(任务状态), d.Status),
                        Content
                    });
                }
            }
            else
            {
                var tIDs = data.Select(it => it.TaskID).ToArray();
                var tasks = ctx.Yqd_Task.Where(it => tIDs.Contains(it.TaskID)).Select(it => new { it.TaskID, it.TaskName, it.LeaderUnitName, it.TaskStatus }).ToList();
                var person = ctx.Yqd_Person.Where(it => it.PersonType == 5).Select(it => new { it.TaskID, it.PersonName }).ToList();
                foreach (var d in data)
                {
                    dynamic t = null;
                    rs.Add(new
                    {
                        d.Num,
                        TaskID = d.TaskID.ToString(),
                        d.SuperviseID,
                        d.CoordinateID,
                        d.CooperativeID,
                        (t = tasks.FirstOrDefault(n => n.TaskID == d.TaskID))?.TaskName,
                        t.LeaderUnitName,
                        PersonName = person.FirstOrDefault(m => m.TaskID == d.TaskID)?.PersonName ?? "",
                        TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                        DealStatus = d.Tag != "钉办" ? Enum.GetName(typeof(任务状态), d.Status) : "",
                        d.Tag,
                        Content = d.Content ?? ""
                    });
                }
            }
            return this.ToJson(new
            {
                success = true,
                totalcount = rs.Count(),
                data = rs.Skip((page - 1) * pagesize).Take(pagesize),
                sql
            });
        }


        [User]
        public ActionResult GetLogList()
        {
            var ItemType = Form.GetInt("ItemType", (int)事项类型.钉办督导);
            var status = Form.GetInt("status");
            var code = Form.GetString("code");
            var year = Form.GetInt("year");
            var taskID = Form.GetInt("TaskID");
            var key = Form.GetString("key");
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 6);
            var sql = "1=1";
            var zx = (事项类型)ItemType == 事项类型.专项交办;
            if (status > 0)
            {
                switch ((督导状态)status)
                {
                    case 督导状态.当前待办:
                        sql += " and [SuperviseID] not in(select [ItemID] from Yqd_Assign where ItemType=" + (int)事项类型.钉办督导 + ")";
                        break;
                    case 督导状态.正常推进:
                        sql += " and [SuperviseID] in(select [ItemID] from Yqd_Assign where ItemType=" + (int)事项类型.钉办督导 + ") and [Status] in(" + (int)任务状态.预警 + "," + (int)任务状态.正常推进 + "," + (int)任务状态.滞后 + ")";
                        break;
                    case 督导状态.滞后:
                        sql += " and [Status]=" + (int)任务状态.滞后;
                        break;
                    case 督导状态.已完成:
                        sql += " and [Status]=" + (int)任务状态.已完成;
                        break;
                    case 督导状态.钉办事项:
                        if (ItemType == (int)事项类型.钉办督导)
                            sql += " and [SuperviseType]=" + (int)督导类型.钉办;
                        break;
                }
            }
            if (code.Trim() != "")
            {
                sql += zx ? " and SuperviseID in(select ItemID from Yqd_Assign where ItemType =" + (int)事项类型.专项交办 + " and LeadUnit={0})" : " and TaskID in(select TaskID from Yqd_Task where LeaderUnitCode={0})";
            }
            if (key.Trim() != "" && !zx)
            {
                sql += " and TaskID in(select TaskID from Yqd_Task where lower(ltrim(rtrim([TaskName]))) like {1})";
            }
            if (year > 0)
            {
                sql += " and year(Instime)=" + year;
            }
            switch ((事项类型)ItemType)
            {
                case 事项类型.钉办督导:
                    sql += " and [SuperviseType]!=" + (int)督导类型.钉办;
                    sql = "select TaskID from Yqd_Supervise where " + sql + " and isdel=0 order by Instime desc";
                    break;
                case 事项类型.协同管理:
                    sql = "select TaskID from Yqd_Coordinate where " + sql + " and isdel=0 order by Instime desc";
                    break;
                case 事项类型.精准督查:
                    sql = "select TaskID from Yqd_ExactSupervise where isDel=0 and " + sql + "order by Instime desc";
                    break;
                case 事项类型.专项交办:
                    sql = "select SuperviseID from Yqd_SpecialSupervise where isDel=0 and " + sql + " and TaskType=" + (int)专项类型.专项交办 + " order by Instime desc";
                    break;
                case 事项类型.专项督查:
                    sql = "select SuperviseID from Yqd_SpecialSupervise where isDel=0 and " + sql + " and TaskType=" + (int)专项类型.专项督查 + " order by Instime desc";
                    break;
            }
            var tIDs = ctx.Database.SqlQuery<long>(sql, code, "%" + key.ToLower().Trim() + "%");
            var tasks = new List<dynamic>();
            if (zx)
            {
                var sp = ctx.Yqd_SpecialSupervise.Where(it => tIDs.Contains(it.SuperviseID)).Select(it => new { it.TaskID, it.SuperviseID, it.TemplateID, it.TemplateData });
                var ids = sp.Select(it => it.TemplateID).ToArray();
                var tps = ctx.Yqd_SpecialTemplate.Where(it => ids.Contains(it.TemplateID)).Select(it => new { it.TemplateID, it.Fields }).ToList();
                foreach (var r in sp)
                {
                    var f = tps.FirstOrDefault(it => it.TemplateID == r.TemplateID);
                    string FieldID = "", FieldName = "", FieldValue = "";
                    if (f != null && f.Fields.HasValue())
                    {
                        var o = JArray.Parse(f.Fields)[0];
                        FieldID = o["FieldID"]?.ToString();
                        FieldName = o["Name"]?.ToString() ?? "";
                    }
                    if (FieldID != "" && r.TemplateData.HasValue())
                    {
                        FieldValue = JObject.Parse(r.TemplateData)[FieldID]?.ToString() ?? "";
                    }
                    tasks.Add(new
                    {
                        TaskID = r.SuperviseID,
                        TaskName = FieldName + "：" + FieldValue
                    });
                }
            }
            else
            {
                tasks.AddRange(ctx.Yqd_Task.Where(it => tIDs.Contains(it.TaskID)).Select(it => new { it.TaskID, it.TaskName }));
            }
            sql = "[IsJb]=" + (zx ? 1 : 0);
            if (tIDs.Count() > 0) sql += "and [TaskID] in('" + string.Join("','", tIDs) + "')";
            else sql += " and TaskID=-1";
            var (totalcount, rs) = ctx.Database.SqlPager<Yqd_TaskLog>((page - 1) * pagesize, pagesize, "*", sql, "[Instime] desc");
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = rs.Select(it => new
                {
                    TaskID = it.TaskID.ToString(),
                    TaskName = tasks.FirstOrDefault(m => it.TaskID == m.TaskID)?.TaskName ?? "",
                    Content = it.Content ?? "",
                    Instime = it.Instime.ToString("yyyy.M.d HH:mm:ss")
                })
            });
        }

        [User]
        public ActionResult GetDDCount()
        {
            var year = Form.GetInt("Year", 0);
            var Leader = Form.GetString("Leader", "王健");
            var TaskType = Form.GetString("TaskType", "");
            var taskIDs = new List<long>();
            var task = ctx.Yqd_Task.Where(it => it.IsShow);
            if (year > 0)
            {
                task = task.Where(it => it.Year == year + "");
            }
            if (TaskType != "")
            {
                task = task.Where(it => ("," + it.TaskType + ",").Contains("," + TaskType + ","));
            }
            if (Leader != "王健")
            {
                var code = ctx.Yqd_Unit.Where(it => it.Leader == Leader).Select(it => it.UnitCode).ToList();
                taskIDs.AddRange(task.Where(it => code.Contains(it.LeaderUnitCode) || it.ConnectMan == Leader).Select(it => it.TaskID));
            }
            var tIDs = task.Select(it => it.TaskID).ToArray();
            var rs = ctx.Yqd_Supervise.Where(it => it.IsDel==0 && tIDs.Contains(it.TaskID));
            if (taskIDs.Count > 0) rs.Where(it => taskIDs.Contains(it.TaskID));
            if (year > 0) rs = rs.Where(it => it.Instime.Year == year);
            var tids = rs.Select(it => it.TaskID).ToArray();
            var r = rs.Select(it => new { it.SuperviseID, it.TaskID, it.Status, it.SuperviseType, it.IsRead }).ToList();
            var dd = r.Where(it => it.SuperviseType == 督导类型.督导);
            var ddsx = dd.Select(it => it.TaskID).Distinct().Count();
            var dqdb = dd.Where(it => it.Status == 任务状态.正常推进 || it.Status == 任务状态.滞后 || it.Status == 任务状态.预警).Select(it => it.TaskID).Distinct().Count();
            var yzh = dd.Where(it => it.Status == 任务状态.滞后).Select(it => it.TaskID).Distinct().Count();
            var ywj = dd.Where(it => it.Status == 任务状态.已完成).Select(it => it.TaskID).Distinct().Count();
            var db = r.Where(it => it.SuperviseType == 督导类型.钉办);
            var dbsx = db.Select(it => it.TaskID).Distinct().Count();
            var dbyjs = db.Where(it => it.IsRead).Select(it => it.TaskID).Distinct().Count();
            var dbwjs = db.Where(it => !it.IsRead).Select(it => it.TaskID).Distinct().Count();
            return this.ToJson(new
            {
                success = true,
                dbsx,
                dbyjs,
                dbwjs,
                ddsx,
                dqdb,
                yzh,
                ywj
            });
        }

        [User]
        public ActionResult GetTaskLog()
        {
            var taskID = Form.GetLong("TaskID");
            var zx = Form.GetBool("zx", false);
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize",10);
            var sql = "[TaskID]=" + taskID.ToString() + " and [IsJb]=" + (zx ? 1 : 0);
            var (totalcount, rs) = ctx.Database.SqlPager<Yqd_TaskLog>((page - 1) * pagesize, pagesize, "*", sql, "[Instime] desc");
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = rs.Select(it => new
                {
                    TaskID = it.TaskID.ToString(),
                    Content = it.Content ?? "",
                    Instime = it.Instime.ToString("yyyy.M.d HH:mm:ss")
                })
            });
        }
    }
}
